package com.wq.httpclientcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wq.httpclientcore.constants.CacheConstants;
import com.wq.httpclientcore.entities.po.ApiConfig;
import com.wq.httpclientcore.entities.po.AuthConfig;
import com.wq.httpclientcore.entities.req.query.ApiConfigREQ;
import com.wq.httpclientcore.mapper.ApiConfigMapper;
import com.wq.httpclientcore.service.ApiConfigService;
import com.wq.httpclientcore.service.AuthConfigService;
import com.wq.httpclientcore.utils.QueryWrapperBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ApiConfigServiceImpl extends ServiceImpl<ApiConfigMapper, ApiConfig> implements ApiConfigService {

    @Autowired
    private AuthConfigService authConfigService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<ApiConfig> list(ApiConfigREQ req) {
        req.setOrderByField("updated_at");
        LambdaQueryWrapper<ApiConfig> apiConfigLambdaQueryWrapper = QueryWrapperBuilder.queryWrapper(ApiConfig.class, req);
        List<ApiConfig> apiConfigList = list(apiConfigLambdaQueryWrapper);
        enrichApiConfigWithAuthConfig(apiConfigList);
        return apiConfigList;
    }

    @Override
    public Page<ApiConfig> pageList(ApiConfigREQ req) {
        req.setOrderByField("updated_at");
        LambdaQueryWrapper<ApiConfig> apiConfigLambdaQueryWrapper = QueryWrapperBuilder.queryWrapper(ApiConfig.class, req);
        Page<ApiConfig> page = Page.of(req.getPageNo(), req.getPageSize());
        Page<ApiConfig> result = page(page, apiConfigLambdaQueryWrapper);
        enrichApiConfigWithAuthConfig(result.getRecords());
        return result;
    }

    @Override
    public boolean saveApiConfig(ApiConfig apiConfig) {
        boolean result = baseMapper.insertApiConfig(apiConfig) > 0;
        if (result) {
            // 缓存单个 API 配置
            String key = CacheConstants.API_CONFIG_PREFIX + apiConfig.getId();
            redisTemplate.opsForValue().set(key, apiConfig, CacheConstants.API_CONFIG_EXPIRE_MINUTES, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public boolean updateApiConfig(ApiConfig apiConfig) {
        boolean result = baseMapper.updateApiConfigById(apiConfig);
        if (result) {
            // 更新缓存
            String key = CacheConstants.API_CONFIG_PREFIX + apiConfig.getId();
            redisTemplate.opsForValue().set(key, apiConfig, CacheConstants.API_CONFIG_EXPIRE_MINUTES, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public boolean removeApiConfigs(List<Long> ids) {
        boolean result = this.removeByIds(ids);
        if (result) {
            // 删除缓存
            ids.forEach(id -> {
                String key = CacheConstants.API_CONFIG_PREFIX + id;
                redisTemplate.delete(key);
            });
        }
        return result;
    }

    private void enrichApiConfigWithAuthConfig(List<ApiConfig> apiConfigList) {
        List<AuthConfig> authConfigList = authConfigService.list();
        List<Long> authIds = authConfigList.stream().map(AuthConfig::getId).collect(Collectors.toList());
        Map<Long, AuthConfig> longAuthConfigMap = authConfigService.id2PO(authIds);
        apiConfigList.forEach(apiConfig -> {
            apiConfig.setAuthConfig(longAuthConfigMap.get(apiConfig.getAuthConfigId()));
        });
    }
}